<!-- eslint-disable vue/multi-word-component-names -->
<template>
    <!-- 确认订单选择地址 -->
    <van-address-list v-if="action == 'select'" v-model="active" :list="list" default-tag-text="默认" @add="onAdd"
        @edit="onEdit" @select="CartSelect" />
    <!-- 会员中心点击进入收获地址 -->
    <van-address-list v-else v-model="active" :list="list" default-tag-text="默认" @add="onAdd" @edit="onEdit"
        @select="onSelect" />
</template>

<script setup>
import { getCurrentInstance, onBeforeMount, ref, reactive } from 'vue';

const { proxy } = getCurrentInstance();
// console.log(proxy.$business.value)

// 接收关键词参数
var state = proxy.$route.query.action ?? '';
let action = ref(state)

// 收获地址列表
let list = reactive([])
let active = ref(0)     // 标识 是否是默认地址

// 但页面一加载进来的时候就触发挂载前的生命周期函数
onBeforeMount(() => {
    AddressList()
})

const AddressList = async () => {
    // 发起请求
    var result = await proxy.$POST({
        url: '/address/index',
        params: { busid: proxy.$business.value.id }
    })

    // 要么是出错 要么没数据
    if (result.code == 0) {
        proxy.$fail(result.msg)
        return false
    }

    result.data.map((item) => {
        // 找出默认的收获地址
        if (item.status == '1') {
            active.value = item.id
        }

        // 重组收获地址结构
        list.push({
            id: item.id,
            name: item.consignee,
            tel: item.mobile,
            address: `${item.region_text} ${item.address}`,
            isDefault: item.status == '1' ? true : false
        })
    })
}

// 添加收获地址
const onAdd = async () => {
    proxy.$router.push('/address/add')
}

// 编辑收获地址
const onEdit = async (item) => {
    proxy.$router.push({ path: '/address/edit', query: { id: item.id } })
}

// 切换默认的收获地址
const onSelect = async (item) => {
    var result = await proxy.$POST({
        url: '/address/check',
        params: {
            busid: proxy.$business.value.id,
            id: item.id
        }
    })

    if (result.code == 0) {
        proxy.$fail(result.msg)
        return false
    }

    // 成功就修改默认的状态
    list.map(value => {
        value.isDefault = false

        if (value.id == item.id) value.isDefault = true
    })
}

// 确认订单切换地址
const CartSelect = async (item) => {
    item.region_text = item.address

    // 将选择的收获地址存入到cookie中
    proxy.$cookies.set('address', item)

    proxy.$router.go(-1)
}
</script>